<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\model\Export;
use app\model\AgentBalanceLog as Model;
use think\Request;

class AgentBalanceLog extends Controller
{

    /**
     * @api {GET} /admin/agentBalanceLog/list 代理商充值记录
     */
    public function list(Request $request)
    {
        $typeInList = [
            // 代理商充值记录
            'recharge' => [
                BALANCE_AGENT_RECHARGE,
                BALANCE_ONLINE_RECHARGE,
                BALANCE_CHANGE_APPLY,
            ],
            // 代理佣金记录
            'commission' => \app\model\AgentBalanceLog::commission(),
            // 预付扣款记录
            'expense' => [
                BALANCE_MOBILE_RECHARGE,// 话费充值
                BALANCE_MOBILE_REFUND,  // 话费退款
                BALANCE_COUPON_EXPENSE, // 权益卡充值
                BALANCE_COUPON_REFUND,  // 权益卡退款
                BALANCE_FILM_EXPENSE,   // 电影充值
                BALANCE_FILM_REFUND,    // 电影退款
                BALANCE_OILCARD_EXPENSE,// 油卡充值
                BALANCE_OILCARD_REFUND, // 加油退款
                BALANCE_POWER_EXPENSE,  // 电费充值
                BALANCE_POWER_REFUND,   // 电费退款
            ],
        ];
        if (!$request->param('list_type') || !isset($typeInList[$request->param('list_type')])) {
            return fail('参数异常');
        }

        $settle_type = $request->param('settle_type');

        $typeIn = $typeInList[$request->param('list_type')];
        $modelQuery = Model::withJoin(['agent' => function ($query) use ($settle_type) {
            $query->withField(['agent.company_name' => 'company_name',
                'agent.username' => 'username',
                'agent.settle_type' => 'settle_type',
            ]);
        }], 'left')
            ->withSearch(['order_id'],$request->param())
            ->with('couponOrder')
//            ->append(['order_id'])
            ->whereIn('type', $typeIn);




        $tableName = $modelQuery->getTable();
        $tableName = array_pop($tableName);

        $where = [];

        if ($settle_type) {
            $where[] =['agent.settle_type', '=', $settle_type];
        }

        if ($request->param('type')) {
            $where[] = ['type', '=', $request->param('type')];
        }
        if ($request->param('name')) {
            $where[] = ['company_name|username', '=', trim($request->param('name'))];
        }
        if ($request->param('created_from')) {
            $where[] = [$tableName . '.created_at', '>=', $request->param('created_from')];
        }
        if ($request->param('created_end')) {
            $where[] = [$tableName . '.created_at', '<=', $request->param('created_end') . ' 23:59:59'];
        }

        if ($where) {
            $modelQuery = $modelQuery->where($where);
        }

        if (!$request->has('is_export')) {
            $list = $modelQuery->order('id desc')->paginate()->each(function ($res){
                $res->append(['settle_type_name','type_name']);
            });
        } else {
            // 导出处理
            $exportTitle = [
                'type' => '类型',
                'username' => '代理商',
                'company_name' => '公司名称',
                'amount' => '金额',
                'remark' => '备注',
                'created_at' => '时间',
            ];

            $list = $modelQuery->order('id desc')->select();
            if ($list->isEmpty()) {
                $list = [];
            } else {
                //$stateArr = Model::$typeArr;
                $stateArr = Model::getTypeArr();
                $list = $list->hidden(['agent'])->toArray();
                foreach ($list as $k => $v) {
                    $list[$k]['type'] = $stateArr[$v['type']];
                    $list[$k]['amount'] = fen2yuan($v['amount']);
                    $list[$k]['company_name'] .= "\t";
                }
            }

            $nameMap = [
                'commission' => '佣金记录',
                'recharge' => '代理商充值记录',
                'expense' => '预付扣款记录'
            ];

            return Export::staticExport($list, $exportTitle, $nameMap[$request->param('list_type')]);
        }
        if (!$list->isEmpty()) {
            $list->hidden(['agent,couponOrder']);

            $list->each(function (\app\model\AgentBalanceLog $agentBalanceLog){
                $agentBalanceLog->append(['order_id']);
                $agentBalanceLog->hidden(['agent,couponOrder']);
            });
        }

        $list = $list->toArray();

        // 统计总数
        $sumArr[0] = 0;
        $typeSumList = $modelQuery->fieldRaw('type,sum(amount) as amount')->group('type')->select();
        $typeSumList = $typeSumList->column('amount', 'type');
        foreach ($typeIn as $k => $v) {
            if (isset($typeSumList[$v])) {
                $sumArr[$v] = $typeSumList[$v];
                $sumArr[0] += $typeSumList[$v];
            } else {
                $sumArr[$v] = 0;
            }
        }
        foreach ($sumArr as $k => $v) {
            $sumArr[$k] = fen2yuan($v);
        }
        $list['sum'] = $sumArr;

        return success('', $list);
    }
}
